package xhwl.hmo.mall.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.Constant;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.bean.ImageItem;
import xhwl.hmo.mall.event.ImageEvent;
import xhwl.hmo.mall.event.LoginEvent;
import xhwl.hmo.mall.event.UpdateUserInfoEvent;
import xhwl.hmo.mall.event.UpgradeEvent;
import xhwl.hmo.mall.http.api.UpdateUserInfoApi;
import xhwl.hmo.mall.http.api.UploadPicApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.ReferralPicBean;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.BitmapUtil;
import xhwl.hmo.mall.utils.DataCleanManager;
import xhwl.hmo.mall.utils.GlideCircleTransform;
import xhwl.hmo.mall.utils.PermisionUtils;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.utils.UpgradeMgr;
import xhwl.hmo.mall.utils.XHLog;
import xhwl.hmo.mall.views.ChineseEditText;
import xhwl.hmo.mall.views.MyDialog;
import xhwl.hmo.mall.views.PopSelectPic;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class SettingsActivity extends BaseActivity implements View.OnClickListener,PopSelectPic.PopSelectBtnClickListener {
    private static final int TAKE_PICTURE = 0x000000;
    private LinearLayout llMain;
    private ImageView img_header;
    private RelativeLayout update_imgheader;
    private LinearLayout name;
    private TextView info_version_tv;
    private RelativeLayout info_version_layout;
    private LinearLayout about_us;
    private LinearLayout convention_buycard;
    private LinearLayout feedback;
    private TextView cache_tv;
    private LinearLayout cache_clear;
    private TextView loginout;
    MyDialog myDialog,nameDialog;
    private String path = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_settings);
    }

    @Override
    public void initViews() {
        initTitleViews();
        llMain= (LinearLayout) findViewById(R.id.llMain);
        img_header = (ImageView) findViewById(R.id.img_header);
        update_imgheader = (RelativeLayout) findViewById(R.id.update_imgheader);
        name = (LinearLayout) findViewById(R.id.name);
        info_version_tv = (TextView) findViewById(R.id.info_version_tv);
        info_version_layout = (RelativeLayout) findViewById(R.id.info_version_layout);
        about_us = (LinearLayout) findViewById(R.id.about_us);
        convention_buycard = (LinearLayout) findViewById(R.id.convention_buycard);
        feedback = (LinearLayout) findViewById(R.id.feedback);
        cache_tv = (TextView) findViewById(R.id.cache_tv);
        cache_clear = (LinearLayout) findViewById(R.id.cache_clear);
        loginout = (TextView) findViewById(R.id.loginout);
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("设置");
    }

    @Override
    public void initListener() {
        update_imgheader.setOnClickListener(this);
        name.setOnClickListener(this);
        info_version_layout.setOnClickListener(this);
        about_us.setOnClickListener(this);
        convention_buycard.setOnClickListener(this);
        feedback.setOnClickListener(this);
        cache_clear.setOnClickListener(this);
        loginout.setOnClickListener(this);
    }

    @Override
    public void loadData() {
        initHead();
        getCache();
        info_version_tv.setText("V"+ AppUtil.getVersionName(mContext));

    }
    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            new UpgradeMgr().checkVersion(SettingsActivity.this);
                        } else {
                            XHLog.e("用户拒绝开启存储");
                            PermisionUtils.dialog(SettingsActivity.this, "读取手机存储");
                        }
                    }

                });
    }
    private void showDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_clear_cache, null);
        TextView tvCancle = (TextView) view.findViewById(R.id.tvCancle);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
                cleanCacheData();
            }
        });
        myDialog = new MyDialog(this, view, Gravity.CENTER);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();

    }
    private void showUpdateNameDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_update_name, null);
        TextView tvCancle = (TextView) view.findViewById(R.id.tvCancle);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        final ChineseEditText etName= (ChineseEditText) view.findViewById(R.id.etName);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name=etName.getText().toString();
                if(!StringUtil.isEmpty(name)){
                    myDialog.dismiss();
                    updateUserInfo(name,"");
                }
                else
                {
                    ToastUtil.showToast(mContext,"请输入姓名");
                }
            }
        });
        myDialog = new MyDialog(this, view, Gravity.CENTER);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();

    }
    private void initHead() {
        if(!StringUtil.isEmpty(SpUtil.getString(SpUtil.MEMBER_HEAD,""))){
            Glide.with(this).load(SpUtil.getString(SpUtil.MEMBER_HEAD,""))
                    .transform(new GlideCircleTransform(this))
                    .error(R.drawable.head)
                    .into(img_header);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.update_imgheader:
                PopSelectPic popfront = new PopSelectPic(SettingsActivity.this, llMain);
                popfront.setCallBack(SettingsActivity.this);
                break;
            case R.id.name:
                showUpdateNameDialog();
                break;
            case R.id.info_version_layout:
                requestPermission();
                break;
            case R.id.about_us:
                AppUtil.startWebViewActivity(mContext,Constant.ABOUT,"");
                break;
            case R.id.convention_buycard:
                AppUtil.startWebViewActivity(mContext,Constant.CONVENTION,"");
                break;
            case R.id.feedback:
                startActivity(new Intent(this,FeedBackActivity.class));
                break;
            case R.id.cache_clear:
                showDialog();
                break;
            case R.id.loginout:
                logout();
                break;
        }
    }

    private void logout() {
        SpUtil.putString(SpUtil.MEMBER_ID,"");
        SpUtil.putString(SpUtil.MEMBER_HEAD,"");
        SpUtil.putString(SpUtil.MEMBER_NAME,"");
        JPushInterface.stopPush(mContext.getApplicationContext());
        EventBus.getDefault().post(new LoginEvent(false));
        finish();
    }
    public void cleanCacheData() {
        String cacheDir=mContext.getCacheDir().toString();
        String fileDir=mContext.getFilesDir().toString();
        String dataPath=cacheDir.substring(0,cacheDir.lastIndexOf("/"));
        String dbDir=dataPath+File.separator+"databases";
        try{
//        DataCleanManager.deleteFilesByDirectory(new File(cacheDir+File.separator+"image"));
            //databases refer to DbConstant
//        DataCleanManager.cleanDatabaseByName(this, "Upgrade.db");
//        DataCleanManager.cleanDatabaseByName(this, "sale.db");
            cache_tv.setText("0.0KB");
        }catch(Exception e){
            e.printStackTrace();
            cache_tv.setText("0.0KB");
        }
    }


    public void getCache() {
        try {
            String cacheDir=mContext.getCacheDir().toString();
            String fileDir=mContext.getFilesDir().toString();
            String dataPath=cacheDir.substring(0,cacheDir.lastIndexOf("/"));
            String dbDir=dataPath+ File.separator+"databases";

            XHLog.e("dbdir="+dbDir+" cachedir="+cacheDir+" fileDir="+fileDir);
            double cacheSize= DataCleanManager.getFolderSize(new File(cacheDir+File.separator+"image"));
            cacheSize+=DataCleanManager.getFolderSize(new File(dbDir));
            String size = DataCleanManager.getFormatSize(cacheSize);
            if (size.equals("0.0Byte")) {
                size = "0.0KB";
            }
            cache_tv.setText(size);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void onEvent(Object obj) {
        if (obj instanceof UpgradeEvent) {
            UpgradeEvent event = (UpgradeEvent) obj;
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(SettingsActivity.this);
            } else if (event.isStartDownload()) {
                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
                ToastUtil.showToast(this, "下载中...");
            }
        }
    }
    //图片处理开始
    private int getAvailableSize() {

        return 1;
    }
    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
                            startActivity(intent);
                        } else {
                            ToastUtil.showToast(mContext, "请打开提示对应权限,否则功能无法使用");
                        }
                    }

                });

    }


    public void takePhoto() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                            File vFile = new File(Constant.SAVE_PIC_PATH, String.valueOf(System.currentTimeMillis()) + ".jpg");
                            if (!vFile.exists()) {
                                File vDirPath = vFile.getParentFile();
                                vDirPath.mkdirs();
                            } else {
                                if (vFile.exists()) {
                                    vFile.delete();
                                }
                            }
                            path = vFile.getPath();
                            Uri cameraUri;
                            if (Build.VERSION.SDK_INT >= 24) {
                                cameraUri = FileProvider.getUriForFile(mContext, "xhwl.hmo.mall.fileProvider", vFile);
                            } else {
                                cameraUri = Uri.fromFile(vFile);
                            }
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                            startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        } else {
                            ToastUtil.showToast(mContext, "请打开提示对应权限,否则功能无法使用");
                        }
                    }

                });

    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if (requestCode == TAKE_PICTURE) {
                ImageItem item = new ImageItem();
                item.sourcePath = path;
                XHLog.e("sourcePath=" + item.sourcePath);
                initImageFiles(item);
            }
        }

    }

    private void initImageFiles(ImageItem item){
        String fileName= BitmapUtil.handleImage(mContext,item.sourcePath,200);
        uploadPic(new File(fileName));

    }
    private void uploadPic(final File file){
        if(file==null)
            return;
        final UploadPicApi api = new UploadPicApi(mContext,new File[]{file});

        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                XHLog.e("开始上传..");
            }

            @Override
            public void onNext(final ArrayList<ReferralPicBean> picBeanList) {
                if(picBeanList!=null&&picBeanList.size()>0){
                    String url=picBeanList.get(0).getUrl_big();
                    updateUserInfo("",url);
                }
                else{
                    ToastUtil.showToast(mContext,"头像上传失败");
                }

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                ToastUtil.showToast(mContext,"头像上传失败");
            }
        });
    }

    private void updateUserInfo(final String name, final String url) {
        UpdateUserInfoApi api=new UpdateUserInfoApi(SpUtil.getString(SpUtil.MEMBER_MOBILE,""),name,url);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if(resp.isOk()){
                    if(!StringUtil.isEmpty(url)){
                        SpUtil.putString(SpUtil.MEMBER_HEAD,url);
                        Glide.with(SettingsActivity.this).load(url)
                                .transform(new GlideCircleTransform(SettingsActivity.this))
                                .error(R.drawable.head)
                                .into(img_header);
                    }
                    if(!StringUtil.isEmpty(name)){
                        SpUtil.putString(SpUtil.MEMBER_NAME,name);
                    }
                    EventBus.getDefault().post(new UpdateUserInfoEvent());
                    ToastUtil.showToast(mContext,"修改成功");
                }
                else
                {
                    ToastUtil.showToast(mContext,resp.message);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myDialog!=null&&myDialog.isShowing()){
            myDialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
    }
}
